package AwsSQS;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.*;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class TesteSQS {

    public static final String ACCESS_KEY = "AKIAJICRH6ZVS7ENHQMA";
    public static final String SECRET_KEY = "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";
    private static String filaUrl;

    public static void main(String[] args) throws Exception {

        /*
         * This credentials provider implementation loads your AWS credentials
         * from a properties file at the root of your classpath.
         *
         * Important: Be sure to fill in your AWS access credentials in the
         * AwsCredentials.properties file before you try to run this sample.
         * http://aws.amazon.com/security-credentials
         */

        AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
        AmazonSQS sqs = new AmazonSQSClient(credentials);

        try {

            //PARA LISTAR AS FILAS DA CONTA OU CRIAR HE NECESSARIO DEFINIR UMA REGIAO
            Region saoPaulo = Region.getRegion(Regions.SA_EAST_1);
            sqs.setRegion(saoPaulo);

            System.out.println("===========================================");
            System.out.println("INICIANDO COM O USO DO SERVICO DE FILAS AWS");
            System.out.println("===========================================\n");

            // PROCESSO PARA A CRIACAO DE UMA FILA(QUEUE) 
            //System.out.println("INICIANDO A CRIACAO DA FILA");
            //CreateQueueRequest createQueueRequest = new CreateQueueRequest("FilaTeste");
            //O RETORNO HE A URL DA FILA CRIADA
            //String filaTesteUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

            // LISTANDO AS FILAS DA REGIAO DEFINIDA ACIMA
            System.out.println("LISTANDO AS FILAS DESTA CONTA NA REGIAO ESPECIFICADA");
            for (String queueUrl : sqs.listQueues().getQueueUrls()) {
                System.out.println("QueueUrl: " + queueUrl);
                filaUrl = queueUrl;
            }

            // ENVIANDO UMA MENSAGEM
//            System.out.println("ENVIANDO UMA MESAGEM PARA A FILA CRIADA");
//            sqs.sendMessage(new SendMessageRequest(filaTesteUrl, "TEXTO DA MENSAGEM ENVIADO"));

            // RECEBENDO MENSAGENS
            //HE NECESSARIO INFORMAR A URL DA FILA QUE SE QUER OBTER AS MENSAGENS
            System.out.println("RECEBENDO MENSAGENS DA FILA");

            //REQUEST DA FILA
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(filaUrl);
            //NECESSARIO SETAR A QUANTIDADE DE MENSAGENS QUE VAMOS RECUPERAR. 
            //QUANDO NAO SETEI SO TROUXE UMA.
            receiveMessageRequest.setMaxNumberOfMessages(10);

            ReceiveMessageResult msgResult = new ReceiveMessageResult();
            msgResult = sqs.receiveMessage(receiveMessageRequest);

            GetQueueAttributesResult queueAtributesResult = new GetQueueAttributesResult();
            GetQueueAttributesRequest queueRequest = new GetQueueAttributesRequest(filaUrl);
            queueAtributesResult = sqs.getQueueAttributes(queueRequest);

            Map<String, String> atributos = queueAtributesResult.getAttributes();

            for (Entry<String, String> reqAtributos : atributos.entrySet()) {
                System.out.println("  Atributo da Fila");
                System.out.println("    Nome:  " + reqAtributos.getKey());
                System.out.println("    Valor: " + reqAtributos.getValue());
            }

            List<Message> messages = msgResult.getMessages();

            System.out.println("TAMANHO DA LISTA DE MENSAGENS RECEBIDA: " + messages.size());

            for (Message message : messages) {
                System.out.println("Message");
                System.out.println("MessageId:     " + message.getMessageId());
                System.out.println("ReceiptHandle: " + message.getReceiptHandle());
                System.out.println("MD5OfBody:     " + message.getMD5OfBody());
                System.out.println("Body:          " + message.getBody());
                
            }

//            // Delete a message
//            System.out.println("Deleting a message.\n");
//            String messageRecieptHandle = messages.get(0).getReceiptHandle();
//            sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

//            // Delete a queue
//            System.out.println("Deleting the test queue.\n");
//            sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));

        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which means your request made it "
                    + "to Amazon SQS, but was rejected with an error response for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with SQS, such as not "
                    + "being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            
        }
    }
}
